package com.jiaquyun.jcyx.main.mine

import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.entity.OrderGood
import com.jiaquyun.jcyx.entity.UserInvoiceHistory
import com.jiaquyun.jcyx.entity.UserInvoiceOrder
import com.jiaquyun.jcyx.entity.UserYongLog
import com.jiaquyun.jcyx.jetpack.mode.MineViewModel
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.image.loadCenterImage
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_mine_invoice.*
import java.text.DecimalFormat


class MineInvoiceFragment : OwnerViewModeFragment<MineViewModel>() {

    companion object {
        const val KEY_COLLECT_ACTION = "KEY_COLLECT_ACTION"
        fun newInstance(action: Int): MineInvoiceFragment {
            val bundle = Bundle().apply {
                putInt(KEY_COLLECT_ACTION, action)
            }
            return MineInvoiceFragment().apply {
                arguments = bundle
            }
        }
    }

    private val mInvoiceHistoryAdapter =
        object :
            BaseQuickAdapter<UserInvoiceHistory, BaseViewHolder>(R.layout.item_invoice_history) {
            override fun convert(holder: BaseViewHolder, item: UserInvoiceHistory) {
                holder.setText(R.id.tvInvoiceHistoryPrice, "￥${item.invoice_money}")
                    .setText(
                        R.id.tvInvoiceHistoryTime,
                        TimeUtils.millis2String(item.createtime * 1000)
                    )
                    .setText(
                        R.id.tvInvoiceHistoryStatus,
                        if (item.status == 1) "待审核" else if (item.status == 2) "已生成" else "已提交"
                    )
            }
        }

    private val mInvoiceOrderAdapter = object :
        BaseQuickAdapter<UserInvoiceOrder, BaseViewHolder>(R.layout.item_invoice_order) {
        init {
            addChildClickViewIds(R.id.cbInvoiceOrderOpt)
        }

        override fun convert(holder: BaseViewHolder, item: UserInvoiceOrder) {
            var count: Int = 0
            item.order_goods.forEach {
                count += it.goods_num
            }
            holder.setText(R.id.tvInvoiceOrderTime, item.createtime)
                .setText(
                    R.id.tvInvoiceOrderPrice,
                    "共${count}件，共可开票金额￥${item.order_amount}"
                )
            holder.getView<CheckBox>(R.id.cbInvoiceOrderOpt).isChecked = item.isSelected

            val adapter = object :
                BaseQuickAdapter<OrderGood, BaseViewHolder>(R.layout.item_invoice_order_goods) {
                override fun convert(holder: BaseViewHolder, item: OrderGood) {
                    holder.setText(R.id.tvInvoiceOrderGoodsName, item.goods_name)
                        .setText(R.id.tvInvoiceOrderGoodsNum, "x${item.goods_num}")
                        .setText(R.id.tvInvoiceOrderGoodsPrice, "￥${item.goods_price}")
                        .getView<ImageView>(R.id.ivInvoiceOrderGoodsIcon)
                        .loadCenterImage(item.image ?: "")
                }
            }
            holder.getView<RecyclerView>(R.id.rvInvoiceOrderBody).apply {
                layoutManager = LinearLayoutManager(context)
            }.adapter = adapter.apply {
                setNewInstance(item.order_goods)
            }
        }
    }


    private val mAction: Int by lazy {
        arguments?.getInt(KEY_COLLECT_ACTION) ?: 0
    }


    override fun viewModel(): MineViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_mine_invoice

    override fun initView() {
        rvMineInvoiceBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = if (mAction == 1)
            mInvoiceHistoryAdapter.apply {
                setOnItemClickListener { _, _, position ->
                    val itemData = getItem(position)
                    viewModel.userInvoiceQuery(itemData.invoice_no)
                }
            }
        else mInvoiceOrderAdapter.apply {
            setOnItemChildClickListener { _, view, position ->
                val itemData = getItem(position)
                if (view.id == R.id.cbInvoiceOrderOpt) {
                    val item = itemData.apply {
                        isSelected = (view as CheckBox).isChecked
                    }
                    mInvoiceOrderAdapter.setData(position, item)
                    updateBottom()
                }
            }
        }


        if (mAction == 1) {
            clMineInvoiceBottom.visibility = View.GONE
        } else {
            clMineInvoiceBottom.visibility = View.VISIBLE
        }

        cbMineInvoiceAll.setOnCheckedChangeListener { _, isChecked ->

            val data = mInvoiceOrderAdapter.data.flatMap {
                mutableListOf(it.apply { isSelected = isChecked })
            }.toMutableList()
            mInvoiceOrderAdapter.setNewInstance(data)

            updateBottom()
        }
        tvMineInvoiceSettle.setOnClickListener {
            val orderIds = mInvoiceOrderAdapter.data.filter { it.isSelected }.flatMap {
                mutableListOf(it.id)
            }.toIntArray()
            InvoiceSubmitActivity.open(tvMineInvoicePrice.text.toString(), orderIds)
        }
    }

    override fun initData() {
        if (mAction == 1) {
            clMineInvoiceBottom.visibility = View.GONE
            viewModel.userInvoiceHistory()
        } else {
            clMineInvoiceBottom.visibility = View.VISIBLE
            viewModel.userInvoiceOrder()
        }
    }

    override fun onRefreshLoad() {
        if (mAction == 1) {
            clMineInvoiceBottom.visibility = View.GONE
            viewModel.userInvoiceHistory()
        } else {
            clMineInvoiceBottom.visibility = View.VISIBLE
            viewModel.userInvoiceOrder()
        }
    }

    override fun initViewMode() {
        viewModel.userInvoiceHistoryLiveDate.observe(viewLifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mInvoiceHistoryAdapter.setNewInstance(data)
        })
        viewModel.userInvoiceOrderLiveDate.observe(viewLifecycleOwner, { response ->
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mInvoiceOrderAdapter.setNewInstance(data)
            updateBottom()
        })
        viewModel.userInvoiceQueryLiveDate.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?:return@observe
            InvoiceDetailsActivity.open(data)
        })
    }

    private fun updateBottom() {
        val data = mInvoiceOrderAdapter.data
            ?: return
        var price = 0.00
        data.filter { it.isSelected }.forEach {
            price += it.order_amount.toDouble()
        }
        tvMineInvoicePrice.text = StringBuilder("￥")
            .append(DecimalFormat(("############0.00")).format(price))

        cbMineInvoiceAll.isChecked =
            data.filter { it.isSelected }.size == data.size && data.size != 0
    }


    private fun createEmptyView(): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null)
    }

    private fun createFooterView(): View = TextView(requireContext()).apply {
        layoutParams = FrameLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            ConvertUtils.dp2px(30f)
        )
        gravity = Gravity.CENTER
        textSize = 13f
        text = "没有更多数据"
        setTypeface(null, Typeface.BOLD)
        setTextColor(ColorUtils.getColor(R.color.FF_666666))
    }

}